<template>
	<el-row style="width: 80%; margin: 0 auto; position: relative; top: 60px">
		<el-col>
			<el-form :inline="true" style="display: flex; justify-content: center">
				<el-row>
					<el-col>
						<el-form-item label-width="5px">
							<el-input v-model="name" clearable class="search-input" :placeholder="hotPlaceholder" @clear="load" />
						</el-form-item>
						<el-form-item label-width="5px">
							<el-button type="primary" :icon="Search" @click="handleSearch"></el-button>
						</el-form-item>
					</el-col>
				</el-row>
			</el-form>
		</el-col>

		<el-col :span="20" style="background-color: rgba(255, 255, 255, 0.5); border-radius: 8px; padding: 16px; position: relative; margin: 0 auto 20px">
			<el-row :gutter="24" style="display: flex; align-items: center">
				<el-col :span="18" style="margin-left: 100px">
					<el-row :gutter="16">
						<el-col v-for="(video, index) in recommendedVideos" :key="index" :span="8" style="margin-bottom: 24px">
							<div class="recommend-item" style="background: #ffffff" @click="handleClick(video)">
								<el-image :src="video.img" style="width: 100%; height: 180px; border-radius: 8px; object-position: center" fit="contain" />
								<div class="recommend-title" style="height: 48px; margin: 8px 0 4px">
									{{ video.name }}
								</div>
								<div class="recommend-info">
									<span style="font-size: 12px; color: #666"> <i class="el-icon-view"></i> {{ video.click }} 播放 </span>
								</div>
							</div>
						</el-col>
					</el-row>
				</el-col>

				<el-col :span="3">
					<el-button type="primary" icon="RefreshRight" size="small" style="height: 36px; padding: 0 16px; min-width: auto" @click="refreshRecommend">
						换一换
					</el-button>
				</el-col>
			</el-row>
		</el-col>

		<el-col style="padding-bottom: 20px">
			<el-button :type="sortField === 'composite' ? 'primary' : 'default'" @click="sortBy('composite')"> 综合排序 </el-button>
			<el-button :type="sortField === 'click' ? 'primary' : 'default'" @click="sortBy('click')"> 最多播放 </el-button>
			<el-button :type="sortField === 'createTime' ? 'primary' : 'default'" @click="sortBy('createTime')"> 最新发布 </el-button>
		</el-col>
		<el-col v-for="item in tableData" :key="item.id" :span="12">
			<el-card class="card-item" shadow="hover">
				<div class="clickable-area" @click="handleClick(item)">
					<el-image style="width: 100%; height: 200px; border-radius: 5px" :src="item.img" fit="contain" />
					<div class="card-content">
						<h3 class="card-title">{{ item.name }}</h3>
						<p class="card-description">{{ item.des }}</p>
					</div>
				</div>

				<div class="card-meta" style="position: relative">
					<el-avatar :size="24" :src="item.user?.avatar || 'https://via.placeholder.com/24'"></el-avatar>
					<span class="meta-text">
						{{ item.user?.username || '未知用户' }}
					</span>
					<span class="meta-text">{{ item.createTime }}</span>
					<span class="play-count" style="position: absolute; right: 16px; bottom: 0"> 播放量：{{ item.click }} </span>
				</div>
			</el-card>
		</el-col>
	</el-row>
</template>

<script setup>
import { reactive, ref } from 'vue'
import { Search } from '@element-plus/icons-vue'
import request from '@/utils/request'
import { ElMessage } from 'element-plus'
import 'md-editor-v3/lib/style.css'
import router from '@/router'

const headerTitle = ref()
const pageNum = ref(1)
const pageSize = ref(10)
const total = ref(0)
const tableData = ref([])
const multipleSelection = ref([])
const disabled = ref(true)
const userList = ref([])
const name = ref('')
const uid = ref('')
const statu = ref('')
const formSize = ref('default')
const ruleFormRef = ref()
const sortField = ref('')
const initialLoad = ref(true)
const hotPlaceholder = ref('输入视频名称')
const recommendedVideos = ref([])

// 表单数据定义
const form = reactive({
	id: undefined,
	name: undefined,
	img: undefined,
	video: undefined,
	des: undefined,
	click: 0,
	uid: undefined,
	statu: '未审核',
	createTime: undefined
})

// 表单校验规则
const rules = reactive({
	name: [{ required: true, message: '必选项不能为空', trigger: 'blur' }],
	img: [{ required: true, message: '必选项不能为空', trigger: 'change' }],
	video: [{ required: true, message: '必选项不能为空', trigger: 'change' }],
	des: [{ required: true, message: '必选项不能为空', trigger: 'blur' }],
	uid: [{ required: true, message: '必选项不能为空', trigger: 'change' }]
})

const getRandomRecommend = async () => {
	try {
		const res = await request.get('/video/random')
		recommendedVideos.value = res.data
	} catch (error) {
		ElMessage.error('获取推荐视频失败')
	}
}

const refreshRecommend = () => {
	getRandomRecommend()
}

// 排序方法
const sortBy = field => {
	sortField.value = sortField.value === field ? '' : field // 点击相同按钮时取消排序
	pageNum.value = 1
	load()
}

// 分页查询方法（初始化方法，页面加载成功以后就调用的方法）
const load = async () => {
	// 获取用户数据（移到外层，只执行一次）
	if (userList.value.length === 0) {
		const resuser = await request.get(`/user`)
		userList.value = resuser.data
	}

	// 初始加载时获取热度最高的视频
	if (initialLoad.value) {
		initialLoad.value = false
		// 获取综合得分最高的视频名称
		const hotRes = await request.get('/video/topComposite')
		if (hotRes.data) {
			hotPlaceholder.value = hotRes.data
		}
	}

	// 统一获取视频数据
	const res = await request.get('/video/home', {
		params: {
			pageNum: pageNum.value,
			pageSize: pageSize.value,
			name: name.value,
			uid: uid.value,
			statu: statu.value,
			sortField: sortField.value
		}
	})

	// 处理分页数据
	pageNum.value = res.data.current
	pageSize.value = res.data.size
	total.value = res.data.total

	// 关联用户信息（使用缓存数据）
	tableData.value = res.data.records.map(video => ({
		...video,
		user: userList.value.find(user => user.id === video.uid) || {}
	}))

	await getRandomRecommend()
}

const handleSearch = () => {
	if (name.value.trim() === '') {
		name.value = hotPlaceholder.value
	}
	load()
}

// 加载页面初始化调用load方法
load()

// 翻页方法
const handleCurrentChange = current => {
	pageNum.value = current
	load()
}
// 多选按钮处理方法
const handleSelectionChange = val => {
	multipleSelection.value = val
	disabled.value = val.length === 0
}

// 批量导入读数据写到后端数据库中
const beforeBatchUpload = async file => {
	let fd = new FormData()
	fd.append('file', file)
	await request.post('/video/batch/upload', fd, {
		headers: {
			'Content-Type': 'multipart/form-data'
		}
	})
	ElMessage({
		showClose: true,
		message: '上传成功',
		type: 'success'
	})
	await load()
}

const change = async row => {
	await request.put(`/video/${row.id}`, row)
	ElMessage({
		showClose: true,
		message: '操作成功',
		type: 'success'
	})
	await load()
}
const $route = router

// 增加播放量
const handleClick = async item => {
	try {
		// 同时执行两个请求
		await Promise.all([request.put(`/video/click/${item.id}`), request.post(`/video/recordHistory/${item.id}`)])
		handleDetail(item.id)
	} catch (error) {
		console.error('操作失败:', error)
		handleDetail(item.id) // 即使失败也继续跳转
	}
}

// 播放视频
const handleDetail = async id => {
	$route.push(`/front/video/detail?id=${id}`)
}
</script>

<style scoped lang="scss">
.card-container {
	padding: 20px;
}

.card-item {
	margin-bottom: 20px;
	border-radius: 8px;
	overflow: hidden;
	transition:
		transform 0.3s ease,
		box-shadow 0.3s ease;
}

.card-item:hover {
	transform: translateY(-5px);
	box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.card-content {
	padding: 16px;
}

.card-title {
	font-size: 18px;
	font-weight: bold;
	margin-bottom: 8px;
	color: #333;
}

.card-description {
	font-size: 14px;
	color: #666;
	line-height: 1.5;
	display: -webkit-box;
	-webkit-line-clamp: 2; /* 限制为两行 */
	-webkit-box-orient: vertical;
	overflow: hidden;
	text-overflow: ellipsis; /* 超出部分显示省略号 */
	height: 42px; /* 固定高度（两行） */
}

.card-meta {
	display: flex;
	align-items: center;
	margin-top: 10px;
	padding: 0 16px;
	position: relative;
	min-height: 40px;
}

.meta-text {
	font-size: 12px;
	color: #999;
	margin-left: 8px;
}

.clickable-area {
	cursor: pointer;
	margin-bottom: 10px;
	transition: transform 0.2s;
}

.clickable-area:active {
	transform: scale(0.98);
}

.play-count {
	position: absolute;
	right: 16px;
	bottom: 8px;
	font-size: 12px;
	color: #666;
	display: flex;
	align-items: center;
	gap: 4px;
	background: rgba(0, 0, 0, 0.05);
	padding: 2px 8px;
	border-radius: 20px;
}

.el-button--primary {
	transition: all 0.3s ease;
}

.recommend-item {
	cursor: pointer;
	transition: transform 0.2s;
	display: flex;
	flex-direction: column;
	align-items: center;
	border-radius: 8px;
	overflow: hidden;
	height: 220px; /* 固定卡片总高度，形成正方形区域 */

	&:hover {
		transform: translateY(-3px);
	}
}

.el-image {
	width: 100% !important;
	height: 150px !important; /* 图片区域固定为正方形比例 */
}

.el-col:nth-child(2) .el-button {
	/* 按钮垂直居中调整 */
	vertical-align: middle;
	/* 按钮动效优化 */
	transition:
		transform 0.2s ease,
		box-shadow 0.2s ease;
	&:hover {
		transform: scale(1.02);
		box-shadow: 0 2px 8px rgba(0, 122, 255, 0.15);
	}
}

.recommend-item {
	height: auto;
	border-radius: 8px;
	box-shadow: 0 1px 4px rgba(0, 0, 0, 0.06);
	transition:
		transform 0.2s ease,
		box-shadow 0.2s ease;

	&:hover {
		transform: translateY(-5px);
		box-shadow: 0 4px 12px rgba(0, 122, 255, 0.15);
	}
}

.recommend-title {
	/* 优化文本截断样式 */
	display: -webkit-box;
	-webkit-line-clamp: 2;
	-webkit-box-orient: vertical;
	overflow: hidden;
	text-overflow: ellipsis;
	margin: 8px 12px; /* 增加左右内边距 */
	height: 44px; /* 调整行高匹配 */
}

.recommend-info {
	padding: 0 12px 12px; /* 增加底部内边距 */
	text-align: left; /* 改为左对齐 */
	display: flex;
	align-items: center;
	gap: 4px;

	.el-icon-view {
		font-size: 14px;
		color: #999;
	}
}
</style>
